import { queryString, toast, cache, rep } from "@/utils"
import { appConfig } from "@/config"

// 接口请求
export const request = (opt) => {
	console.log('接口请求地址:', opt.url)
	// 默认请求配置
	const defaultConfig = {
		method: opt.method,
		showLoading: opt.showLoading === undefined ? true : opt.showLoading,
		baseUrl: appConfig.BASE_URL
	}
	const finalConfig = defaultConfig
	finalConfig.showLoading && uni.showLoading({ title: "加载中...", mask: true })
	return new Promise((resolve, reject) => {
		// 无感刷新
		/* const timestamp = (new Date()).getTime() / 1000
		const expire = localStorage.getExpire() / 1000
		if(timestamp > expire - 1800){
			resolve(reload(opt))
			return
		} */
		uni.request({
			method: finalConfig.method,
			url: finalConfig.baseUrl + opt.url + queryString(opt.params),
			data: opt.data,
			header: (() => {
				const token = cache.get.token()
				let config = {
					'Content-Type': 'application/json;charset=utf-8',
				}
				if(token){
					config.token = token
				}
				return config;
			})(),
			success: r => {
				if(r.statusCode === 500){
					toast("服务器异常")
					// reject("服务器异常")
					return
				}else if(r.statusCode === 401){
					cache.remove.token()
					toast("登录信息已过期，请重新登录")
					rep('/pages/login/index')
					reject("鉴权失败")
				}
				const { code, msg } = r.data
				if(code === 0) toast(msg)
				resolve(r.data)
			},
			fail: err => {
				reject(err)
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	})
}

// 文件上传
// url, filePath, formData = {}, files
export const uploadFile = (opt) => {
	const config = (() => {
		let baseConf = {
			url: opt.url,
			header: (() => {
				const token = cache.get.token()
				let config = {
					// 'Content-Type': 'multipart/form-data',
				}
				if(token){
					config.token = token
				}
				return config;
			})(),
            name: 'file',
			formData: opt.formData
		}
		
		if(opt.filePath){
			baseConf.filePath = opt.filePath
		}
		if(opt.files){
			baseConf.files = opt.files
		}
		return baseConf
	})()
    return new Promise((resolve, reject) => {
        uni.uploadFile({
			...config,
            success: r => {
                console.log(r,'文件-上传-')
                resolve(r.data)
            },
            fail: err => {
                console.log(err, '文件上传失败')
            }
        })
    })
}
// 下载
export const downloadFile = (url) => {
	uni.downloadFile({
		url: appConfig.imgCDN+url, //仅为示例，并非真实的资源
		success: (res) => {
			if (res.statusCode === 200) {
				uni.saveFile({
				  tempFilePath: res.tempFilePath,
				  success: function (res) {
					var savedFilePath = res.savedFilePath;
					toast(savedFilePath)
					console.log('保存成功', res);
				  }
				});
			}
		}
	});
}